package com.atguigu.gmall.all.controller;

import com.atguigu.gmall.activity.client.ActivityFeignClient;
import com.atguigu.gmall.common.result.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

@Controller
public class SeckillController {

    @Autowired
    private ActivityFeignClient activityFeignClient;

    //  显示秒杀列表
    @GetMapping("seckill.html")
    public String seckillList(Model model){
        //  通过远程调用获取商品秒杀列表集合数据
        Result result = this.activityFeignClient.findAll();
        //  后台需要存储 ${list}
        model.addAttribute("list",result.getData());
        //  返回秒杀列表页面名称.
        return "seckill/index";
    }

    //  显示秒杀详情：th:href="'/seckill/'+${item.skuId}+'.html'"
    @GetMapping("seckill/{skuId}.html")
    public String seckillItem(@PathVariable Long skuId,Model model){
        //  通过远程调用获取商品秒杀详情数据
        Result result = this.activityFeignClient.getSeckillGoods(skuId);
        //  后台要存储一个item 对象。
        model.addAttribute("item",result.getData());
        //  返回秒杀详情页面名称.
        return "seckill/item";
    }

    //  秒杀的排队页面。
    //  http://activity.gmall.com/seckill/queue.html?skuId=23&skuIdStr=c81e728d9d4c2f636f067f89cc14862c
    @GetMapping("seckill/queue.html")
    public String queue(HttpServletRequest request){
        //  获取skuId
        String skuId = request.getParameter("skuId");
        //  获取下单码
        String skuIdStr = request.getParameter("skuIdStr");
        //  保存数据.
        request.setAttribute("skuId",skuId);
        request.setAttribute("skuIdStr",skuIdStr);
        // 返回页面名称.
        return "seckill/queue";
    }

    //  下订单页面：
    //  /seckill/trade.html
    @GetMapping("/seckill/trade.html")
    public String seckillTrade(Model model){
        //  后台存储 userAddressList ，detailArrayList ，totalNum，totalAmount
        //  需要远程调用;
        Result<Map<String,Object>> result = this.activityFeignClient.trade();

        //  判断：判断code 是否是 200
        if (result.isOk()){
            //  存储数据
            model.addAllAttributes(result.getData());
            return "seckill/trade";
        }else {
            //  存储数据
            model.addAttribute("message","下订单失败.");
            return "seckill/fail";
        }


    }

}
